package com.example.userservice.service;

import com.alibaba.fastjson.JSON;
import com.example.userservice.mapper.OrgMapper;
import com.example.userservice.mapper.UserMapper;
import com.example.userservice.pojo.Org;
import com.example.userservice.pojo.User;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
public class OrgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public User queryById(Long id){
//        int i = 1/0;
//        return userMapper.selectByPrimaryKey(id);
        return null;
    }

    public List<User> queryUserList() {
        List<User> userList = userMapper.queryUserList();
        return userList;
    }

    public List<Org> getOrgTree() {
        String orgString1 = stringRedisTemplate.opsForValue().get("org:1");
        //redis是否命中
        if(!StringUtils.isNullOrEmpty(orgString1)){
            List<Org> orgs = JSON.parseArray(orgString1, Org.class);
            return orgs;
        }
        //未命中
        //1.数据库查询数据
        List<Org> orgs = orgMapper.selectAll();
        //2.赋值给redis
        String orgsJsonString = JSON.toJSONString(orgs);
        stringRedisTemplate.delete("org:1");
        stringRedisTemplate.opsForValue().set("org:1",orgsJsonString,1000000, TimeUnit.DAYS);
        /*List<Org> collect  = orgs.stream()
                .filter(new Predicate<Org>() {
                    @Override
                    public boolean test(Org item) {
                        return item.getParentId().equals(0L);
                    }
                })
                .map(new Function<Org, Org>() {
                    @Override
                    public Org apply(Org org) {
                        org.setChildren(getOrgChildres(orgs, org));
                        return null;
                    }
                })
                .toList();*/
        //3.返回数据
        return orgs;
    }

    private List<Org> getOrgChildres(List<Org> orgs, Org org) {
        List<Org> collect = orgs.stream()
                                .filter(new Predicate<Org>() {
                                    @Override
                                    public boolean test(Org org) {
                                        return false;
                                    }
                                })
                                .collect(Collectors.toList());
        return null;
    }
}
